package org.jflame.auth.authz;

import java.io.Serializable;

/**
 * 多url权限表示类,即由多个{@link UrlPermit}组合为表示一个权限
 * 
 * @author charles.zhang
 */
public class MultiUrlPermit extends Permit implements Serializable {

    private static final long serialVersionUID = -2979075439435035038L;

    private PermitSet<UrlPermit> permitSet;

    public MultiUrlPermit() {
    }

    public MultiUrlPermit(String name) {
        this(name, null);
    }

    public MultiUrlPermit(String name, PermitSet<UrlPermit> permissions) {
        setName(name);
        this.permitSet = permissions;
    }

    @Override
    public boolean implies(Permit p) {
        if (p instanceof MultiUrlPermit) {
            MultiUrlPermit that = (MultiUrlPermit) p;
            return that.getName()
                    .equals(this.getName())
                    || permitSet.implies(that.getPermitSet()
                            .getPermissions());
        } else if (p instanceof UrlPermit) {
            return permitSet.implies((UrlPermit) p);
        }
        return false;
    }

    public PermitSet<UrlPermit> getPermitSet() {
        return permitSet;
    }

    public void setPermitSet(PermitSet<UrlPermit> permitSet) {
        this.permitSet = permitSet;
    }

    /**
     * 用给定规则字符串构造一个MultiUrlPermit.
     * <p>
     * 权限url字符串格式: /path[methods...][,...] 示例:<br>
     * <pre>
     * /user,/goods/info,/employee[post,get],/public/*
     * </pre>
     *
     * @param name 权限标识名
     * @param multiUrls url
     * @return
     */
    public static MultiUrlPermit create(String name, String multiUrls) {
        String[] urls = multiUrls.split(",");
        PermitSet<UrlPermit> perms = new PermitSet<>();
        for (String u : urls) {
            perms.add(UrlPermit.create(u));
        }
        return new MultiUrlPermit(name, perms);
    }

}
